import wmi
import hashlib

import base64
from pyDes import *
import os


class Register:
    def __init__(self):
        self.Des_key = "posdvsgt"  # Key,需八位
        self.Des_IV = "\x11\2\x2a\3\1\x27\2\0"  # 自定IV向量

        self.pre_str = "HJDKAH"  # 前缀
        self.suf_str = "SDFDTY"  # 后缀

        # 获取机器码，机器码由以下四部分拼接组成
        # 1、CPU序列号  2、MAC地址 3.硬盘序列号 4.主板序列号
        self.m_wmi = wmi.WMI()

    # cpu序列号 16位
    def get_cpu_serial(self):
        cpu_info = self.m_wmi.Win32_Processor()
        if len(cpu_info) > 0:
            serial_number = cpu_info[0].ProcessorId
            return serial_number
        else:
            return "ABCDEFGHIJKLMNOP"

    # 硬盘序列号 15位
    def get_disk_serial(self):
        disk_info = self.m_wmi.Win32_PhysicalMedia()
        if len(disk_info) > 0:
            serial_number = disk_info[0].SerialNumber.strip()
            return serial_number
        else:
            return "WD-ABCDEFGHIJKL"

    # mac地址 12位
    def get_mac_address(self):
        for network in self.m_wmi.Win32_NetworkAdapterConfiguration():
            mac_address = network.MacAddress
            if mac_address != None:
                return mac_address.replace(":", "")
        return "ABCDEF123456"

    # 主板序列号 14位
    def get_board_serial(self):
        board_info = self.m_wmi.Win32_BaseBoard()
        if len(board_info) > 0:
            board_id = board_info[0].SerialNumber.strip().strip('.')
            return board_id
        else:
            return "ABCDEFGHIJKLMN"

    # 拼接生成机器码
    def getMachineCode(self):
        mac_address = self.get_mac_address()
        cpu_serial = self.get_cpu_serial()
        disk_serial = self.get_disk_serial()
        board_serial = self.get_board_serial()

        combine_str = self.pre_str + mac_address + cpu_serial + disk_serial + board_serial + self.suf_str
        combine_byte = combine_str.encode("utf-8")
        machine_code = hashlib.md5(combine_byte).hexdigest()
        return machine_code.upper()

    # DES+base64加密
    def Encrypted(self, tr):
        k = des(self.Des_key, CBC, self.Des_IV, pad=None, padmode=PAD_PKCS5)
        EncryptStr = k.encrypt(tr)
        return base64.b32encode(EncryptStr)  # 转base64编码返回

    # 获取注册码，验证成功后生成注册文件
    def regist(self):
        machine_code = self.getMachineCode()
        print('请复制', machine_code, '到注册机获取注册码')
        key_code = input('请输入激活码:')
        if key_code:
            encrypt_code = self.Encrypted(machine_code.encode("utf-8"))
            md5_code = hashlib.md5(encrypt_code).hexdigest().upper()
            key_code = key_code.upper()

            if md5_code == key_code:
                print("激活成功！")
                with open('register.bin', 'w') as f:
                    f.write(key_code)
                return True
            else:
                print("激活码错误，请重新输入！")
                return self.regist()
        else:
            return False

    # 打开程序先调用注册文件，比较注册文件中注册码与此时的硬件信息编码后是否一致
    def checkAuthored(self):
        machine_code = self.getMachineCode()
        encrypt_code = self.Encrypted(machine_code.encode("utf-8"))
        md5_code = hashlib.md5(encrypt_code).hexdigest().upper()

        if os.path.exists("./register.bin"):
            with open("./register.bin", "r") as f:
                key_code = f.read()
            if key_code == md5_code:
                return True
        return False


# if __name__ == '__main__':
#     register = Register()
#     while (not register.checkAuthored()):
#         register.regist()
#
#     input('Press Enter to exit…')


def getActiveCode(machine_code):
    Des_key = "posdvsgt"  # Key,需八位
    Des_IV = "\x11\2\x2a\3\1\x27\2\0"

    k = des(Des_key, CBC, Des_IV, pad=None, padmode=PAD_PKCS5)
    EncryptStr = k.encrypt(machine_code.encode("utf-8"))
    encrypt_code = base64.b32encode(EncryptStr)  # 转base64编码返回
    active_code = hashlib.md5(encrypt_code).hexdigest().upper()
    return active_code


if __name__ == '__main__':
    machine_code = input('请输入机器码:')
    active_code = getActiveCode(machine_code)
    print('激活码:', active_code)

    input('Press Enter to exit…')